package com.cyt.sys.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * Created by sunli on 2019/4/15.
 */
public class Md5Base64 {

    private static BASE64Encoder encoder = new BASE64Encoder();// 加密
    private static BASE64Decoder decoder = new BASE64Decoder();// 解密

    //加密MD5和base64加密
    public static String encryptMd5BASE64(String headContent,String versionId){

        if(headContent==null || "".equals(headContent) || versionId==null || "".equals(versionId) ){
            return "";
        }else{
            // 加密对象，指定加密方式
            MessageDigest md5 = null;
            try {
                md5 = MessageDigest.getInstance("md5");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            // 准备要加密的数据
            byte[] b = headContent.getBytes();
            // 加密
            byte[] digest = md5.digest(b);
            // 十六进制的字符
            char[] chars = new char[]{'0', '1', '2', '3', '4', '5',
                    '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
            StringBuffer sb = new StringBuffer();
            // 处理成十六进制的字符串(通常)
            for (byte bb : digest) {
                sb.append(chars[(bb >> 4) & 15]);
                sb.append(chars[bb & 15]);
            }

            String newString=headContent+","+versionId;
            byte[] key = newString.getBytes();
            return encoder.encodeBuffer(key);
        }
    }

    //解密
    public static String decryptBASE64(String outputStr){

        //还原加密的字符串
        String restoreEncryptLisence=outputStr.substring(8).replace(" ","=");
        String decryptInfo=null;
        if(restoreEncryptLisence==null || "".equals(restoreEncryptLisence)){
            return "";
        }else{
            byte[] key = new byte[0];
            try {
                key = decoder.decodeBuffer(restoreEncryptLisence);
                String a= new String(key);
                String[] b =a.split(",");
                decryptInfo=b[2];
            } catch (IOException e) {
                e.printStackTrace();
            }
            return decryptInfo;
        }
    }
}
